package com.sunlg.smarthome.ui.main;

import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.sunlg.smarthome.R;
import com.sunlg.smarthome.base.App;
import com.sunlg.smarthome.base.C;
import com.sunlg.smarthome.contract.presenter.LoginPresenter;
import com.sunlg.smarthome.contract.LoginContract;
import com.sunlg.smarthome.utils.PreferHelper;

public class WelcomeActivity extends AppCompatActivity
        implements LoginContract.View{

    private PreferHelper mPreferHelper;
    private LoginContract.Presenter presenter;
    private boolean isFirstStart;

    private Handler handler = new Handler();

    private PreferHelper preferHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //全屏显示
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_welcome);

        mPreferHelper = App.getInstance().getPreferHelper();
        presenter = new LoginPresenter();
        presenter.attachView(this);

        preferHelper = new PreferHelper(App.getInstance(), "setting");
        if(preferHelper.getBoolean("is_first_start", true)){
            preferHelper.setBoolean("is_push", true);
            preferHelper.setBoolean("is_first_start", false);
        }

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                silenceLogin();
            }
        }, 2000);
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void forward() {
        Intent intent = new Intent(WelcomeActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void showError(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
        finish();
    }

    /**
     * 静默登录
     */
    private void silenceLogin(){
        if(mPreferHelper.getBoolean(C.PreKey.IS_REMEMBER, false)
                && mPreferHelper.getBoolean(C.PreKey.IS_AUTO_LOGIN, false)){
            String username = mPreferHelper.getString(C.PreKey.USER_NAME, "username");
            String password = mPreferHelper.getString(C.PreKey.PASSWORD, "password");

            presenter.login(username, password);
        }else {
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.dettachView();
    }
}
